﻿#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include "QXmlOper.h"
#include "CModelMng.h"
#include "CSqlOper.h"
#include "CGlobal.h"
#include "Public.h"
#include "CLogOper.h"

CModelMng::CModelMng()
{
	initCfg();//初始化xml文件
	m_bDbInit=CSqlOper::instance().initSql();
	m_pIsApiServer = new CIsapiServer();
	connect(m_pIsApiServer, &CIsapiServer::sigNewRequest, this, &CModelMng::slotNewRequest);
	m_pIsApiServer->setNetworkParameter(g_sListernIp, g_nListernPort);
	QString sErrMsg = "";
	m_pIsApiServer->startServer(sErrMsg);
	m_pExportResultTh = new CExportResultTh();
	m_pExportResultTh->ThreadStart();
}

CModelMng::~CModelMng()
{
	if (m_pIsApiServer != nullptr)
	{
		delete m_pIsApiServer;
		m_pIsApiServer = nullptr;
	}
	if (m_pExportResultTh)
	{
		delete m_pExportResultTh;
		m_pExportResultTh = nullptr;
	}
}

void CModelMng::initCfg()
{
	QString m_strSystemLogDir = QCoreApplication::applicationDirPath();
	QString filename = m_strSystemLogDir + "/DLL/SensorSeriesCfg/SensorSeriesCfg.xml";
	XmlOper::SetXmlName(filename);
	QVector<QString>vecHttpUrl;      //http文件服务地址前缀
	vecHttpUrl = ReadXmlS("SensorSeries,HTTPURL,url,url");
	if (vecHttpUrl.size() >= 1)
	{
		g_sHttpUrl = vecHttpUrl[0];
	}

	QVector<QString>vecPdfUrl;
	vecPdfUrl = ReadXmlS("SensorSeries,OUTPATH,path,path");
	if (vecPdfUrl.size() >= 1)
	{
		g_sPdfOutputPath = vecPdfUrl[0];
	}
	QVector<QString>vecIp;      //IsapiSever监听地址
	QVector<QString>vecPort;    //IsapiSever监听端口号
	QVector<QString>vecResultTime;
	QVector<QString>vecCustomName;
	vecIp = ReadXmlS("SensorSeries,ISAPISERVER,ip,ip");
	vecPort = ReadXmlS("SensorSeries,ISAPISERVER,port,port");
	vecCustomName = ReadXmlS("SensorSeries,CUSTOM,name,name");
	vecResultTime = ReadXmlS("SensorSeries,RESULTTIME,time,time");
	if (vecIp.size() >= 1)
	{
		g_sListernIp = vecIp[0];
	}
	if (vecPort.size() >= 1)
	{
		g_nListernPort = vecPort[0].toInt();
	}
	if (vecCustomName.size() >= 1)
	{
		g_sCustomName = vecCustomName[0];
	}
	if (vecResultTime.size() >= 1)
	{
		g_nResultTime = vecResultTime[0].toInt();
	}
}

void CModelMng::extractJsonFromMultipart(QByteArray requestData)
{
	QString sRequest = QString::fromUtf8(requestData);
	//首先先判断是否Post /Alarm请求
	if (!sRequest.contains("POST /Alarm"))
	{
		return;
	}
	else
	{
		int nStartindex = sRequest.indexOf("{");
		int nEndIndex = sRequest.lastIndexOf("}");
		QString sJson = sRequest.mid(nStartindex, nEndIndex - nStartindex + 1);
		QString sIp = "";
		int nChannel = 0;
		QString sChannelName = "";
		QString sDateTime = "";
		QString sAccDirect = "";
		int nTempAlarm = 0;
		int nVibrationAlarm = 0;
		int nVoiceAlarm = 0;
		double dTempValue = 0.0;//温度
		double dRMS = 0.0;//加速度
		double dTimePeakToPeak = 0.0;//时域峰峰值
		double dEnvPeakToPeak = 0.0;//(包络谱)峰峰值
		double dEnvFaultFrqMulti = 0.0;//(包络谱)故障频率的倍频
		double dEnvBladePassFrqMulti = 0.0;//(包络谱)转频的倍频
		double dBladePassEdgeFrqMultiSum = 0.0;//转频的边频倍频个数之和
		double dTimeDomainKurtosis = 0.0;//时域峭度
		double dShapeFactor = 0.0;//形状因子
		QJsonDocument doc = QJsonDocument::fromJson(sJson.toUtf8());
		CDevDataSensorSeries* pDevData = nullptr;
		if (!doc.isNull())
		{
			if (doc.isObject())
			{
				QJsonObject jsonObject = doc.object();
				if (jsonObject.contains("ipAddress"))
				{
					sIp = jsonObject["ipAddress"].toString();
					if (!m_mapDev.contains(sIp))
					{
						return;
					}
					pDevData = m_mapDev[sIp]->m_pModelMange->m_pDev->m_pDevData;
				}
				if (jsonObject.contains("channelID"))
				{
					nChannel = jsonObject["channelID"].toInt();
					sChannelName = pDevData->m_mapChannel[nChannel].sChannelName;
				}
				if (jsonObject.contains("dateTime"))
				{
					sDateTime = QDateTime::fromString(jsonObject["dateTime"].toString(), "yyyy-MM-ddThh:mm:ss+08:00").toString("yyyy/MM/dd hh:mm:ss");
				}
				if (jsonObject.contains("AudioDetectionInfo"))
				{
					QJsonObject audioDetectionInfo = jsonObject["AudioDetectionInfo"].toObject();
					if (audioDetectionInfo.contains("accDirect"))
					{
						sAccDirect = audioDetectionInfo["accDirect"].toString();
					}
					if (audioDetectionInfo.contains("tempResult"))
					{
						if (audioDetectionInfo["tempResult"].toString() == "abnormal")
						{
							nTempAlarm = 1;
						}
						else
						{
							nTempAlarm = 0;
						}
					}
					if (audioDetectionInfo.contains("vibrationResult"))
					{
						if (audioDetectionInfo["vibrationResult"].toString() == "abnormal")
						{
							nVibrationAlarm = 1;
						}
						else
						{
							nVibrationAlarm = 0;
						}
					}
					if (audioDetectionInfo.contains("voiceprintResult"))
					{
						if (audioDetectionInfo["voiceprintResult"].toString() == "abnormal")
						{
							nVoiceAlarm = 1;
						}
						else
						{
							nVoiceAlarm = 0;
						}
					}
					if (audioDetectionInfo.contains("tempValue"))
					{
						dTempValue = audioDetectionInfo["tempValue"].toDouble();
					}
					if (audioDetectionInfo.contains("RMS"))
					{
						dRMS = audioDetectionInfo["RMS"].toDouble();
					}
					if (audioDetectionInfo.contains("timePeakToPeak"))
					{
						dTimePeakToPeak = audioDetectionInfo["timePeakToPeak"].toDouble();
					}
					if (audioDetectionInfo.contains("envFaultFrqMulti"))
					{
						dEnvFaultFrqMulti = audioDetectionInfo["envFaultFrqMulti"].toDouble();
					}
					if (audioDetectionInfo.contains("envBladePassFrqMulti"))
					{
						dEnvBladePassFrqMulti = audioDetectionInfo["envBladePassFrqMulti"].toDouble();
					}
					if (audioDetectionInfo.contains("bladePassEdgeFrqMultiSum"))
					{
						dBladePassEdgeFrqMultiSum = audioDetectionInfo["bladePassEdgeFrqMultiSum"].toDouble();
					}
					if (audioDetectionInfo.contains("envPeakToPeak"))
					{
						dEnvPeakToPeak = audioDetectionInfo["envPeakToPeak"].toDouble();
					}
					if (audioDetectionInfo.contains("timeDomainKurtosis"))
					{
						dTimeDomainKurtosis = audioDetectionInfo["timeDomainKurtosis"].toDouble();
					}
					if (audioDetectionInfo.contains("shapeFactor"))
					{
						dShapeFactor = audioDetectionInfo["shapeFactor"].toDouble();
					}
				}

			}

			//判断推送报警的有效性
			if (nTempAlarm == 0 && nVoiceAlarm == 0 && nVibrationAlarm == 0)
			{
				return;
			}
			//生成报警记录
			QString sErrMsg = "";
			SSensorSeriesAlarmInfo info;
			info.sGuid = createGuid();
			info.sDevGuid = pDevData->m_sDevGuid;
			info.sDevName = pDevData->m_sDevName;
			info.nChannel = nChannel;
			info.sAlarmTime = sDateTime;
			info.sAccDirect = sAccDirect;
			info.nTempAlarm = nTempAlarm;
			info.nVibrationAlarm = nVibrationAlarm;
			info.nVoiceAlarm = nVoiceAlarm;
			info.dTempValue = dTempValue;
			info.dRMS = dRMS;
			info.dTimePeakToPeak = dTimePeakToPeak;
			info.dEnvPeakToPeak = dEnvPeakToPeak;
			info.dEnvFaultFrqMulti = dEnvFaultFrqMulti;
			info.dEnvBladePassFrqMulti = dEnvBladePassFrqMulti;
			info.dBladePassEdgeFrqMultiSum = dBladePassEdgeFrqMultiSum;
			info.dTimeDomainKurtosis = dTimeDomainKurtosis;
			info.dShapeFactor = dShapeFactor;
			info.sBeltName = pDevData->m_sBeltName;
			info.sChannelName = sChannelName;
			CSqlOper::instance().insertSensorSeriesAlarm(info, sErrMsg);

			//插入日志
			SExecLog sDevExecLog;
			sDevExecLog.m_sDevName = A2T("声振温");
			sDevExecLog.m_sFuncName = A2T("报警服务器");
			sDevExecLog.m_sDescriptionl = A2T("%1生成报警事件,通道:%2,维度:%3,温度诊断:%4,振动诊断:%5,声音诊断:%6,温度值:%7,加速度:%8,时域峰峰值:%9,(包络谱)峰峰值:%10,(包络谱)故障频率的倍频:%11,(包络谱)转频的倍频:%12,转频的边频倍频个数之和:%13,时域峭度:%14,形状因子:%15")
				.arg(pDevData->m_sDevName)
				.arg(sChannelName)
				.arg(sAccDirect)
				.arg(nTempAlarm)
				.arg(nVibrationAlarm)
				.arg(nVoiceAlarm)
				.arg(dTempValue)
				.arg(dRMS)
				.arg(dTimePeakToPeak)
				.arg(dEnvPeakToPeak)
				.arg(dEnvFaultFrqMulti)
				.arg(dEnvBladePassFrqMulti)
				.arg(dBladePassEdgeFrqMultiSum)
				.arg(dTimeDomainKurtosis)
				.arg(dShapeFactor);
			sDevExecLog.m_nAlarmLevel = enProcessAlarm;
			CLogOper::instance().addMsg(sDevExecLog);

			//更新报警状态
			if (pDevData->m_mapChannel.contains(nChannel))
			{
				if (nTempAlarm == 1)
				{
					pDevData->m_mapChannel[nChannel].bTempState = false;
					pDevData->m_mapChannel[nChannel].m_dTemp = QDateTime::currentDateTime();
				}
				if (nVibrationAlarm == 1)
				{
					pDevData->m_mapChannel[nChannel].bVibrationState = false;
					pDevData->m_mapChannel[nChannel].m_dVicration = QDateTime::currentDateTime();
				}
				if (nVoiceAlarm == 1)
				{
					pDevData->m_mapChannel[nChannel].bVoiceState = false;
					pDevData->m_mapChannel[nChannel].m_dVoice = QDateTime::currentDateTime();
				}
			}
		}
	}
}

void CModelMng::slotNewRequest(QByteArray &requestData)
{
	extractJsonFromMultipart(requestData);
}